package template

import (
	"flag"
	"fmt"
	"os"
	"strings"
)

var (
	projectNamespace = flag.String("np", "", "模板仓库的完整命名空间 比如: github.com/namespace")
	projectRepo      = flag.String("repo", "", "模板仓库的名字 比如:kelvins-template")
	projectKind      = flag.String("kind", "rpc", "模板应用的类型 比如: rpc,cron,http,queue,proto")
)

func Gen() {
	if *projectNamespace == "" {
		fmt.Fprintln(os.Stderr, "np参数不能为空")
		return
	}
	if *projectRepo == "" {
		fmt.Fprintln(os.Stderr, "repo参数不能为空")
		return
	}
	if *projectKind == "" {
		fmt.Fprintln(os.Stderr, "kind参数不能为空")
		return
	}
	var err error
	var rootDir string
	rootDir, err = os.Getwd()
	if err != nil {
		fmt.Fprintln(os.Stderr, "获取当前目录错误", err)
		return
	}
	// replacer init
	projectReplacer = strings.NewReplacer(signProjectNp, *projectNamespace, signProjectName, *projectRepo)
	projectProto := strings.ReplaceAll(*projectRepo, "-", "_")
	projectProtoReplacer = strings.NewReplacer(signProjectNameProto, projectProto)
	versionReplacer = strings.NewReplacer("{version_common}", VersionCommon, "{version_kelvins}", VersionKelvins)

	// gen template by kind
	switch *projectKind {
	case "rpc":
		rpcKind := new(gRPCKind)
		err = rpcKind.Gen(rootDir)
	case "proto":
		protoKind := new(protoKind)
		err = protoKind.Gen(rootDir)
	case "cron":
		projectReplacer = strings.NewReplacer(signProjectNp, *projectNamespace, signProjectName, *projectRepo+"-cron")
		cronKind := new(cronKind)
		err = cronKind.Gen(rootDir)
	case "queue":
		projectReplacer = strings.NewReplacer(signProjectNp, *projectNamespace, signProjectName, *projectRepo+"-consumer")
		queueKind := new(queueKind)
		err = queueKind.Gen(rootDir)
	case "http", "gin":
		httpKind := new(ginKind)
		err = httpKind.Gen(rootDir)
	default:
		err = fmt.Errorf("应用模板还在路上")
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		if err != nil {
			return
		}
		return
	}
	fmt.Fprintf(os.Stdout, "仓库：%v 类型：%v %v\n", *projectRepo, *projectKind, " 模板创建完成")
}
